<?php

namespace App\Service;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;
use Flaravel\Upload\Fupload;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * 公众号
 */
class MiniProgramService
{
    //优惠券领取成功通知 模板ID
    const COUPON_RECEIVE = '4kL1FG-GTpPdTyqrAZsee6fImiYsUM1dhkgRYoRVRog';

    public  $account;

    public function __construct()
    {
        $this->account = Factory::miniProgram(config('wechat.mini_program.default'));
    }

    /**
     * 绑定手机号发送优惠券消息
     *
     * @param $coupon
     * @param $memberCoupon
     * @param $form_id
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function sendCouponReceive($coupon, $memberCoupon,$form_id)
    {
        if(empty($form_id)) return false;
        if($coupon->type == 2)
        {
            $raiod = floatval($coupon->discount_rate);
            $msg = "绑定手机号送优惠券，全场满{$coupon->full_reduction_amount}元打{$raiod},赶紧去shopping呀！";
        }else if ($coupon->type == 1){
            $msg = "绑定手机号送优惠券，全场满{$coupon->full_reduction_amount}元减少{$coupon->price}元，抓紧时间购买吧";
        }

        $this->sendTemplateMsg(
                $memberCoupon->user->wx_mini_openid,
                self::COUPON_RECEIVE,
                $form_id,
                '/pages/index/index',
                [
                    'keyword1' => $coupon->title,
                    'keyword2' =>$msg ?? $coupon->title,
                    'keyword3' => $memberCoupon->end_time,
                ]
        );
    }

    /**
     * 发送模板消息
     *
     * @param $openid
     * @param $template_id
     * @param $form_id
     * @param $page
     * @param $data
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function sendTemplateMsg($openid, $template_id, $form_id, $page, $data)
    {
         return $this->account->template_message->send([
            'touser' => $openid,
            'template_id' => $template_id,
            'page'  => $page,
            'form_id' => $form_id,
            'data' => $data
        ]);
    }

    /**
     * 生成小程序码
     *
     * @param $json
     * @param string $page
     * @return bool|StreamResponse|int
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function getAccountCode($json, $page = '') {
        $response = $this->account->app_code->getUnlimit($json, ['width' => 430, 'page' => $page]);
        if ($response instanceof StreamResponse) {
            $url = Fupload::upload($response->getBody()->getContents(),'share', 'png');
            return  config('upload.ossUrl').Str::after($url,'com/');
        } else {
            return $response;
        }
    }


    /**
     * 退款
     *
     * @param string $transactionId  微信订单号
     * @param string $refundNo 退款单号
     * @param int $orderAmount 订单金额
     * @param int $refundAmount 退款金额
     * @param array $config 其他信息
     * @return bool
     */
    public function refund($transactionId, $refundNo, $orderAmount, $refundAmount, $config = [])
    {
        try {
            $app = Factory::payment(config('wechat.payment.default'));
            return $app->refund->byTransactionId($transactionId, $refundNo, $orderAmount, $refundAmount, $config);
        } catch (\Exception $exception) {
            Log::info('订单号：'.$refundNo.'退款失败:'.$exception->getMessage());
            return false;
        }
    }
}
